import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:second_hand/pages/login.dart';
import '../../../API/goods/goods.dart';
import '../../../data/shared_preferences_service.dart';

class RecommendList extends StatefulWidget {
  const RecommendList({super.key});
  @override
  _RecommendListState createState() => _RecommendListState();
}

class _RecommendListState extends State<RecommendList> {
  String? token;
  final ScrollController _scrollController = ScrollController();
  bool _isLoading = false;
  bool _showNoMore = false;
  bool _hasMore = true;
  int _page = 1;
  List<Map<String, dynamic>> _goods = [];

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_scrollListener);
    _initialize();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  Future<void> _initialize() async {
    await _loadToken();
    if(token == null) {
      Get.snackbar(
        "错误",
        "未登录，请先登录",
        duration: const Duration(seconds: 5),
      );
      Get.to(()=>LoginPage());
      return;
    }
    await _refreshData();
  }

  Future<void> _loadToken() async {
    token = await SharedPreferencesService.getToken();
  }

  void _scrollListener() {
    final maxScroll = _scrollController.position.maxScrollExtent;
    final currentScroll = _scrollController.position.pixels;
    const scrollThreshold = 100.0; // 提前加载的阈值

    if (currentScroll > maxScroll - scrollThreshold &&
        !_isLoading &&
        _hasMore) {
      _loadData();
    }
  }

  // 修改_refreshData确保重置页码
  Future<void> _refreshData() async {
    //if(reset) {
      setState(() {
        _page = 1; // 重置时先设为1，loadData会处理下一页
        _hasMore = true;
        _showNoMore = false;
        _goods.clear();
      });
    //}
    await _loadData(reset: true); // 强制重置时会请求第1页
  }

  // 修改后的 _loadData 方法
  Future<void> _loadData({bool reset = false}) async {
    if (_isLoading || !_hasMore || token == null) return;

    // 防抖：确保状态更新完成后再执行
    await Future.delayed(Duration.zero);
    setState(() => _isLoading = true);

    try {
      final int requestedPage = reset ? 1 : _page;
      if (kDebugMode) {
        print('正在请求页码: $requestedPage');
      }

      // 添加随机参数防止缓存（测试用）
      final response = await ItemApiService.searchGoods(
        page: requestedPage,
      );

      if (response['code'] == 20041) {
        final data = response['data'];
        final List<dynamic> list = data['list'];
        final int totalItems = data['total'] ?? 0;
        final int totalPages = (totalItems / 16).ceil();
        print('请求页码: $requestedPage');
        print('响应数据长度: ${list.length}');
        print('响应第一条数据ID: ${list.isNotEmpty ? list[0]['id'] : '空'}');
        setState(() {
          if (reset) {
            _goods = List<Map<String, dynamic>>.from(list);
          } else {
            _goods.addAll(List<Map<String, dynamic>>.from(list));
          }

          _hasMore = requestedPage < totalPages;
          _showNoMore = !_hasMore && _goods.isNotEmpty;
          _page = requestedPage + 1; // 强制更新页码
        });

        print('加载成功，当前数据量: ${_goods.length}');
        print('下一页应请求: $_page');
      }
    } catch (e) {
      print('加载失败: $e');
    } finally {
      setState(() => _isLoading = false);
    }
  }

  Color _getStatusColor(String status) {
    switch (status) {
      case 'available':
        return Colors.green;
      case 'sold':
        return Colors.grey;
      case 'trading':
        return Colors.orange;
      default:
        return Colors.black54;
    }
  }
  final String defaultImageUrl = 'https://twt-trade-platform.oss-cn-beijing.aliyuncs.com/242fac3d-0fe2-4b66-9b04-94f339550433.jpg';
  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      onRefresh: _refreshData,
      child: Stack(
        children: [
          CustomScrollView(
            controller: _scrollController,
            physics: const AlwaysScrollableScrollPhysics(),
            slivers: [
              SliverGrid(
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  childAspectRatio: 0.7,
                  crossAxisSpacing: 8.0,
                  mainAxisSpacing: 8.0,
                ),
                delegate: SliverChildBuilderDelegate(
                      (context, index) {
                    final item = _goods[index];
                    return Card(
                      color: Colors.white,
                      margin: const EdgeInsets.all(4.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const SizedBox(height: 4),
                          Center(
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(8.0),
                              child: _buildAdaptiveImage(
                                imageUrl: item['image']?.isNotEmpty ?? false ? item['image'] : defaultImageUrl,
                              ),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.fromLTRB(8.0, 8, 8, 0),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  item['name'],
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                  style: const TextStyle(fontSize: 18),
                                ),
                                SizedBox(height: 1),
                                Text(
                                  '¥${item['price']}',
                                  style: const TextStyle(
                                    color: Colors.red,
                                    fontWeight: FontWeight.bold,
                                    fontSize: 18,
                                  ),
                                ),
                                Text(
                                  item['status'],
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: _getStatusColor(item['status']),
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                  childCount: _goods.length,
                ),
              ),
              // 上拉加载更多指示器
              SliverToBoxAdapter(
                child: _isLoading && _page > 1
                    ? const Padding(
                  padding: EdgeInsets.symmetric(vertical: 20),
                  child: Center(child: CircularProgressIndicator()),
                )
                    : _showNoMore
                    ? _buildNoMoreWidget()
                    : const SizedBox.shrink(),
              )
            ],
          ),
          // 首次加载时的中央指示器
          if (_isLoading && _page == 1)
            const Center(child: CircularProgressIndicator()),
        ],
      ),
    );
  }
  Widget _buildAdaptiveImage({required String imageUrl}) {
    // 判断是否是网络图片
    final isNetworkImage = imageUrl.startsWith('http');

    return isNetworkImage
        ? Image.network(
      imageUrl,
      height: 180,
      width: 180,
      fit: BoxFit.cover,
      loadingBuilder: (context, child, loadingProgress) {
        if (loadingProgress == null) return child;
        return _buildImageLoading();
      },
      errorBuilder: (context, error, stackTrace) {
        return _buildErrorImage();
      },
    )
        : Image.file(
      File(imageUrl),
      height: 180,
      width: 180,
      fit: BoxFit.cover,
      errorBuilder: (context, error, stackTrace) {
        return _buildErrorImage();
      },
    );
  }

  Widget _buildErrorImage() {
    return Image.network(
      defaultImageUrl,
      height: 180,
      width: 180,
      fit: BoxFit.cover,
      errorBuilder: (context, error, stackTrace) {
        return Container(
          height: 180,
          color: Colors.grey[300],
          child: const Center(
            child: Icon(Icons.broken_image, color: Colors.red),
          ),
        );
      },
    );
  }

  Widget _buildImageLoading() {
    return Container(
      height: 180,
      color: Colors.grey[300],
      child: const Center(
        child: SizedBox(
          width: 30,
          height: 30,
          child: CircularProgressIndicator(strokeWidth: 2),
        ),
      ),
    );
  }
  Widget _buildNoMoreWidget() {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 20),
      child: Column(
        children: [
          const Divider(height: 1),
          const SizedBox(height: 16),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(Icons.sentiment_satisfied_alt,
                  color: Colors.grey[400], size: 20),
              const SizedBox(width: 8),
              Text(
                '已经到底了，没有更多了',
                style: TextStyle(
                  color: Colors.grey[600],
                  fontSize: 14,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
        ],
      ),
    );
  }
}